package com.auerdi.ui.fragment.first;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.auerdi.R;
import com.auerdi.adapter.ChatAdapter;
import com.auerdi.base.BaseMainFragment;
import com.auerdi.entity.Chat;
import com.auerdi.event.TabSelectedEvent;
import com.auerdi.listener.OnItemClickListener;
import com.auerdi.ui.fragment.MainFragment;
import com.example.egghttp.RetrofitClient;
import com.example.egghttp.retrofit.AdService;
import com.example.egghttp.retrofit.beans.BOb;
import com.example.egghttp.retrofit.beans.banner.BannerList;
import com.example.egghttp.retrofit.beans.banner.HomeBanner;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.yokeyword.eventbusactivityscope.EventBusActivityScope;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by YoKeyword on 16/6/30.
 */
public class WechatFirstTabFragment extends BaseMainFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.banner)
    Banner banner;
    Unbinder unbinder;
    //    @BindView(R.id.header)
//    RecyclerViewHeader header;
    private Toolbar mToolbar;
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecy;

    private boolean mInAtTop = true;
    private int mScrollTotal;

    private ChatAdapter mAdapter;

    public static WechatFirstTabFragment newInstance() {

        Bundle args = new Bundle();

        WechatFirstTabFragment fragment = new WechatFirstTabFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

//        L.d("hcia", "onCreateView:");

        View view = inflater.inflate(R.layout.wechat_fragment_tab_first, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView(view);
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {


                HomeBanner banner = (HomeBanner) path;
                Picasso.get().load(banner.getImg()).error(R.mipmap.epta).placeholder(R.mipmap.epta).fit().centerInside().into(imageView);
//                                Picasso.get().load(pic).error(R.drawable.logo).placeholder(R.drawable.logo).fit().centerInside().into(imageView);

            }
        });

        RetrofitClient.getClient().create(AdService.class).homebanner("", "")
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .doOnNext(merchantBasicOb -> {
//                        L.d("hcia", "call:");
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<BannerList>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BOb<BannerList> bannerListBOb) {
                        List<HomeBanner> banners = bannerListBOb.getBody().getHomeBanner_list();

                        banner.setImages(banners);
                        banner.start();

                    }
                });
//
//        RetrofitClient.getClient().create(AdService.class).actRep()
//                .subscribeOn(Schedulers.newThread())
//                .observeOn(Schedulers.io())
//                .doOnNext(merchantBasicOb -> {
////                        L.d("hcia", "call:");
//                })
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<BOb<ActrepList>>() {
//                    @Override
//                    public void onCompleted() {
//
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        L.d("hcia", "e:" + e);
//
//                    }
//
//                    @Override
//                    public void onNext(BOb<ActrepList> bannerListBOb) {
//                        List<com.example.egghttp.retrofit.beans.banner.Banner> banners = bannerListBOb.getBody().getActrep();
//
//                        L.d("hcia", "banners.get(0):" + banners.get(0));
//
//
//                    }
//                });


        return view;
    }

    private void initView(View view) {
        mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        mRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh_layout);
        mRecy = (RecyclerView) view.findViewById(R.id.recy);


        EventBusActivityScope.getDefault(_mActivity).register(this);

        mToolbar.setTitle(R.string.home);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);


        mRefreshLayout.setOnRefreshListener(this);

        mRecy.setLayoutManager(new LinearLayoutManager(_mActivity));
        mRecy.setHasFixedSize(true);
        final int space = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0.5f, getResources().getDisplayMetrics());
        mRecy.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.set(0, 0, 0, space);
            }
        });
        mAdapter = new ChatAdapter(_mActivity);
        mRecy.setAdapter(mAdapter);

        mRecy.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mScrollTotal += dy;
                if (mScrollTotal <= 0) {
                    mInAtTop = true;
                } else {
                    mInAtTop = false;
                }
            }
        });

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position, View view, RecyclerView.ViewHolder vh) {
                // 因为启动的MsgFragment是MainFragment的兄弟Fragment,所以需要MainFragment.start()

                // 也可以像使用getParentFragment()的方式,拿到父Fragment来操作 或者使用 EventBusActivityScope
                ((MainFragment) getParentFragment()).startBrotherFragment(MsgFragment.newInstance(mAdapter.getMsg(position)));
            }
        });

        List<Chat> chatList = initDatas();
        mAdapter.setDatas(chatList);
    }

    private List<Chat> initDatas() {
        List<Chat> msgList = new ArrayList<>();

        String[] name = new String[]{"Jake", "Eric", "Kenny", "Helen", "Carr"};
        String[] chats = new String[]{"message1", "message2", "message3", "message4", "message5"};

        for (int i = 0; i < 15; i++) {
            int index = (int) (Math.random() * 5);
            Chat chat = new Chat();
            chat.name = name[index];
            chat.message = chats[index];
            msgList.add(chat);
        }
        return msgList;
    }

    @Override
    public void onRefresh() {
        mRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshLayout.setRefreshing(false);
            }
        }, 2500);
    }


    /**
     * Reselected Tab
     */
    @Subscribe
    public void onTabSelectedEvent(TabSelectedEvent event) {
        if (event.position != MainFragment.FIRST) return;

        if (mInAtTop) {
            mRefreshLayout.setRefreshing(true);
            onRefresh();
        } else {
            scrollToTop();
        }
    }

    private void scrollToTop() {
        mRecy.smoothScrollToPosition(0);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBusActivityScope.getDefault(_mActivity).unregister(this);
        unbinder.unbind();
    }

    //如果你需要考虑更好的体验，可以这么操作
    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }
}
